/*
 * This file is part of ksPlatform
 * 
 * Copyright (c) 2014-2015
 * 
 * This file is dual-licensed under the AGPLv3 (http://www.gnu.org/licenses/agpl-3.0.html) 
 * 
 * If you are unsure which license is appropriate for your use, please contact the sales department
 * at 97041437@qq.com.
 */
package cn.com.ksplatform.base.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.util.StringUtils;

import cn.com.ksplatform.base.page.PageInfoModel;
import cn.com.ksplatform.core.context.PlatformContext;

/**
 * Hibernate基类
 * 
 * @author Simon
 * 
 */
@SuppressWarnings("rawtypes") 
public class BaseHibernateDAO extends HibernateTemplate implements IBaseHibernateDAO {

	private String sessionFactoryName = "sessionFactory";

	/**
	 * 获取Session
	 * 
	 * @return
	 */
	private Session getCurrentSession() {
		SessionFactory sf = PlatformContext.getBean(sessionFactoryName, SessionFactory.class);
		Session session = sf.getCurrentSession();
		return session;
	}

	
	/*
	 * 按属性查找唯一对象，匹配方式为相等
	 * 
	 * @param propertyName
	 * 
	 * @param value
	 * 
	 * @return
	 */
	public Object uniqueResult(Class clazz,String propertyName, Object value) {
		Criterion criterion = Restrictions.eq(propertyName, value);
		Session session = getCurrentSession();
		Object result = session.createCriteria(clazz).add(criterion).uniqueResult();
		return result;
	}

	
	public List findAll(final String hql) {
		return this.findAll(hql, null);
	}

	public List findAll(final String hql, final List values) {
		List result = null;
		Session session = getCurrentSession();
		Query query = session.createQuery(hql);
		if(values!=null){
			initParam(values, query);
		}
		result =query.list();
		//session.close();
		return result;
	}

	/**
	 * hql分页查询
	 * 
	 * @param hql
	 *            查询字符串
	 * @param queryResult
	 *            查询结果
	 * @param values
	 *            查询值
	 * @return
	 */
	public PageInfoModel queryPage(final String hql, final PageInfoModel pim, final List values) {
		//排序
		String orderSql = hql;
		String sortName = pim.getSortName();
		if(StringUtils.hasText(sortName)){
			String sortOrder = pim.getSortOrder();
			String orderType = sortOrder.equals("")? "asc" : sortOrder;
			orderSql += " order by " + sortName +" "+ orderType;
		}
		Session session = getCurrentSession();
		Query query = session.createQuery(orderSql);
		query.setFirstResult(pim.getStarIndex());
		query.setMaxResults(pim.getPageSize());
		if(values!=null){
			initParam(values, query);
		}
		
		pim.setRows(query.list());
		String countHql = "select count(*) " + orderSql; // 封装查询总记录条数
		int allCount = getAllCount(countHql, values); // 总记录条数
		pim.setTotal(allCount);
		return pim;
	}
	/**
	 * 
	 * @param hql
	 * @param pim
	 * @return
	 */
	public PageInfoModel queryPage(final String hql, final PageInfoModel pim) {
		return queryPage(hql, pim, null);
	}

	/**
	 * hql查询得到总查询数目
	 * 
	 * @param hql
	 *            查询字符串
	 * @param values
	 *            查询值
	 * @return
	 */
	private Integer getAllCount(final String hql, final List values) {
		Session session = getCurrentSession();
		Query query = session.createQuery(hql);
		if(values!=null){
			initParam(values, query);
		}
		Number num = (Number) query.uniqueResult();
		Integer result = num.intValue();
		//session.close();
		return result;
	}
	
	/**
	 * 
	 * initParam:初始化查询参数. <br/>
	 * @author Mr.Luoxing
	 * @param values
	 * @param query
	 */
	private void initParam(final List values, Query query) {
		if (values != null) {
			for (int i = 0; i < values.size(); i++) {
				query.setParameter(i, values.get(i));
			}
		}
	}
	
	/**
	 * Hql查询方法
	 * @param hql
	 * @param params
	 * @return
	 */
	public List executeQuery(String hql,Object... params){
		Session session = getCurrentSession();
		Query query = session.createQuery(hql);
		if(params != null && params.length > 0){
			for(int i=0;i<params.length;i++){
				query.setParameter(i, params[i]);
			}
		}
		return query.list();
	}
	/**
	 * Hql更新方法
	 * @param hql
	 * @param params
	 * @return
	 */
	public int executeUpdate(String hql,Object... params){
		Session session = getCurrentSession();
		Query query = session.createQuery(hql);
		if(params != null && params.length > 0){
			for(int i=0;i<params.length;i++){
				query.setParameter(i, params[i]);
			}
		}
		int result = query.executeUpdate();
		return result;
	}
}
